/**
 * @param app
 * @param prefix
 * 给目前所有的路由接口添加前缀
 */
const { getAuthorization } = require('../utils/authorization')
const JWT = require('../utils/jwt')
function addPrefixToRoutes(app,prefix = '/api/v1') {
    // 使用全局中间件
    app.use((req,res,next) => {
        // 所有接口加上默认前缀
        req.url = prefix + req.url
        if(req.url.includes('login')|| req.url.includes('getCaptcha') || req.url.includes('news')) {
            next()
            return;
        }
        const token = getAuthorization(req)
        if(token) {
            const payload = JWT.verify(token)
            if(payload) {
                next()
            } else  {
                res.status(401).send({
                    errCode: '-1',
                    errorInfo: 'token过期或者未授权'
                })
            }
        } else {
            res.status(401).send({
                errCode: '-1',
                errorInfo: 'token过期或者未授权'
            })
        }
    })
}

module.exports = {
    addPrefixToRoutes
}
